﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace T03ChatClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Socket clientSocket;
        private bool isListen;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void BtConnect_Click(object sender, RoutedEventArgs e)
        {
            //必须输入昵称,并未做安全性校验以及政策性校验
            if(string .IsNullOrWhiteSpace(TxtName.Text.Trim()))
            {
                MessageBox.Show("请设置一个聊天昵称");
                return;
            }
            //连接
            if (clientSocket == null)
            {
                try
                {
                    IPAddress ip = IPAddress.Parse("127.0.0.1");
                    IPEndPoint iep = new IPEndPoint(ip,18888);
                    clientSocket = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);
                    //异步 新开线程，处理网络连接
                    clientSocket.BeginConnect(iep,(args)=> {
                        if(args.IsCompleted){
                            byte[] bytesSend = new byte[4096];
                            //访问UI线程的内容，异步更新界面
                            TxtName.Dispatcher.BeginInvoke(new 
                                Action(()=> {
                                    bytesSend = Encoding.UTF8.GetBytes(TxtName.Text.
                                        Trim() + "$");
                                    //如果连接上，设置相关界面
                                    if (clientSocket !=null&&clientSocket.Connected)
                                    {
                                        clientSocket.Send(bytesSend);
                                        TxtName.IsEnabled = false;
                                        TxtSendMsg.Focus();
                                        //启动连接线程
                                        Thread t = new Thread(DataFromServer);
                                        t.IsBackground=true;
                                        t.Start();
                                    }
                                    else
                                    {
                                        MessageBox.Show("服务器以关闭");
                                        clientSocket = null;
                                    }
                                })); ;
                        }
                    },null);
                }
                catch (Exception ex){
                    Debug.WriteLine(ex.ToString());
                }
            }
            else
            {
                MessageBox.Show("已连接服务器");
            }
        }

        

        private void BtnSend_Click(object sender, RoutedEventArgs e)
        {
            if(string.IsNullOrWhiteSpace(TxtSendMsg.Text.Trim()))
            {
                MessageBox.Show("不能发送空内容");
                return; 
            }

            if(clientSocket != null &&clientSocket.Connected)
            {
                byte[] bytesSend = Encoding.UTF8.GetBytes(TxtSendMsg.Text + "$");
                clientSocket.Send(bytesSend);
                TxtSendMsg.Text = "";

            }
            else
            {
                MessageBox.Show("服务器已关闭或未连接");
            }
        }

        private void Window_Activated(object sender, EventArgs e)
        {
            //文本发送框聚焦
            TxtSendMsg.Focus();

        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (clientSocket!=null&&clientSocket .Connected) {
                clientSocket.Send(Encoding.UTF8.GetBytes("$"));
            }
        }
        private void DataFromServer()
        {
            ShowMsg("连接到聊天服务器...");
            isListen = true;
            try
            {
                while (isListen)
                {
                    byte[] bytesFrom = new byte[4096];
                    int len = clientSocket.Receive(bytesFrom);
                    string dataFromServer = Encoding.UTF8.GetString
                        (bytesFrom, 0, len);
                    if (dataFromServer.StartsWith("#") && dataFromServer.EndsWith("#"))
                    {
                        string username = dataFromServer.Substring(1,
                            dataFromServer.Length - 2);
                        this.Dispatcher.BeginInvoke(new Action(() => {
                            MessageBox.Show("用户名【" + username + "】已存在，请重新输入");
                            TxtName.IsEnabled = true;
                            TxtName.Focus();
                        }));
                      
                        isListen = false;
                       
                    }
                    else
                    {
                        //显示信息
                        ShowMsg(dataFromServer);
                    }
                }
            }catch(Exception e)
            {
                isListen = false;
                if (clientSocket != null && clientSocket.Connected)
                    clientSocket.Send(Encoding.UTF8.GetBytes("$"));
                Debug.WriteLine(e.ToString());
            }
        }

        private void ShowMsg(string msg)
        {
            TxtReciveMsg.Dispatcher.BeginInvoke(new Action (()=> {
                TxtReciveMsg.Text += Environment.NewLine + msg;
                TxtReciveMsg.ScrollToEnd();
            }));
        }
    }
}
